// pages/profile/profile.js
const { get, post, syncUserProfile, queryUserProfiles } = require('../../utils/api.js')
const { showError, showSuccess, calculateAge, navigateTo } = require('../../utils/util.js')

Page({
  data: {
    // 页面模式：false=展示模式，true=编辑模式
    isEditMode: false,
    
    // 用户资料展示数据
    userProfile: {
      userNum: 859, // 默认用户编号
      name: '',
      gender: '',
      age: 0,
      height: 0,
      weight: 0,
      bmiDesc: '',
      birthDate: '',
      chineseZodiac: '',
      maritalStatus: '',
      education: '',
      occupation: '',
      isPartyMember: false,
      hometown: '',
      currentResidence: '',
      assets: {
        annualIncome: 0,
        car: '',
        house: ''
      },
      familyMembers: {
        familyType: '',
        fatherDetail: { age: 0, desc: '' },
        motherDetail: { age: 0, desc: '' },
        otherDetail: []
      },
      avatarConfig: null,
      isOnline: false
    },
    
    // 表单数据（编辑模式使用）
    formData: {
      nickname: '林小雨',
      gender: 'female',
      birthday: '1998-01-01',
      height: 165,
      currentCity: '上海',
      education: '硕士',
      occupation: '医生',
      personalStatement: '热爱生活，喜欢旅行和摄影。希望找到一个有趣的灵魂一起探索世界。',
      avatarConfig: {
        faceShape: 'oval',
        hairstyle: 'long_wavy',
        hairColor: 'brown',
        eyeShape: 'almond',
        clothing: {
          category: 'casual',
          item: 'sweater',
          color: 'pink'
        },
        accessories: {
          glasses: 'none',
          hat: 'none',
          jewelry: 'earrings',
          scarf: 'none'
        }
      }
    },

    // 选择器选项
    genderOptions: [
      { text: '男', value: 'male' },
      { text: '女', value: 'female' }
    ],

    educationOptions: [
      { text: '高中及以下', value: 'highschool' },
      { text: '大专', value: 'college' },
      { text: '本科', value: 'bachelor' },
      { text: '硕士', value: 'master' },
      { text: '博士', value: 'doctor' }
    ],

    // 城市数据
    cities: [
      '北京', '上海', '广州', '深圳', '杭州', '南京', '苏州', '成都', '重庆', '武汉',
      '西安', '天津', '青岛', '大连', '厦门', '宁波', '福州', '长沙', '郑州', '济南'
    ],
    filteredCities: [],
    citySearchKeyword: '',

    // 日期选择器
    minDate: new Date(1950, 0, 1).getTime(),
    maxDate: new Date(2010, 11, 31).getTime(),
    selectedDate: new Date(1998, 0, 1).getTime(),

    // 兴趣爱好
    activeCategory: 'sports',
    currentInterests: [],
    selectedInterests: [
      { id: 'travel', name: '旅行', category: 'travel' },
      { id: 'photography', name: '摄影', category: 'art' },
      { id: 'cooking', name: '美食', category: 'food' },
      { id: 'yoga', name: '瑜伽', category: 'sports' }
    ],
    allInterests: {},

    // 弹窗状态
    showGenderPopup: false,
    showDatePopup: false,
    showCityPopup: false,
    showEducationPopup: false,
    showSaveDialog: false,

    // 页面状态
    loading: false,
    hasChanges: false,

    // 计算属性
    genderText: '女',
    birthdayText: '1998-01-01',
    cityText: '上海',
    educationText: '硕士',
    statementLength: 0,
    selectedCity: '上海',

    // 分类激活状态
    sportsActive: 'active',
    musicActive: '',
    travelActive: '',
    foodActive: '',
    readingActive: '',
    movieActive: ''
  },

  onLoad(options) {
    console.log('📱 个人资料页面加载', options)
    
    // 检查是否为编辑模式
    const isEdit = options.edit === 'true'
    this.setData({ isEditMode: isEdit })
    
    if (isEdit) {
      this.initEditMode()
    } else {
      this.initDisplayMode()
    }
  },

  onShow() {
    // 页面显示时重新加载数据
    if (this.data.isEditMode) {
      this.loadProfile()
    } else {
      this.loadUserProfile()
    }
  },

  /**
   * 初始化展示模式
   */
  initDisplayMode() {
    console.log('🎨 初始化展示模式')
    this.loadUserProfile()
  },

  /**
   * 初始化编辑模式
   */
  initEditMode() {
    console.log('✏️ 初始化编辑模式')
    this.initInterests()
    this.initCities()
    this.updateComputedProperties()
    this.loadProfile()
  },

  /**
   * 加载用户资料（展示模式）
   */
  loadUserProfile() {
    console.log('📊 开始加载用户资料')
    this.setData({ loading: true })

    // 调用用户档案查询接口
    queryUserProfiles({
      userNumList: [this.data.userProfile.userNum] // 查询指定用户
    }, {
      showLoading: true,
      loadingTitle: '加载用户资料中...'
    })
      .then(data => {
        console.log('✅ 用户资料加载成功:', data)
        
        if (data.userprofileList && data.userprofileList.length > 0) {
          const userProfile = data.userprofileList[0]
          
          // 处理用户资料数据
          const processedProfile = this.processUserProfileData(userProfile)
          
          this.setData({
            userProfile: processedProfile,
            loading: false
          })
          
          console.log('📋 处理后的用户资料:', processedProfile)
        } else {
          console.warn('⚠️ 未找到用户资料数据')
          this.showEmptyState()
        }
      })
      .catch(error => {
        console.error('❌ 用户资料加载失败:', error)
        this.setData({ loading: false })
        showError('加载用户资料失败，请重试')
        this.showEmptyState()
      })
  },

  /**
   * 处理用户资料数据
   */
  processUserProfileData(rawData) {
    // 计算年龄（如果没有age字段）
    let age = rawData.age
    if (!age && rawData.birthDate) {
      age = this.calculateAgeFromBirthDate(rawData.birthDate)
    }

    // 生成默认头像配置
    const avatarConfig = this.generateDefaultAvatar(rawData.gender)

    return {
      userNum: rawData.userNum,
      name: rawData.name || '未设置',
      gender: rawData.gender || '未设置',
      age: age || 0,
      height: rawData.height || 0,
      weight: rawData.weight || 0,
      bmiDesc: rawData.bmiDesc || '未设置',
      birthDate: rawData.birthDate || '未设置',
      chineseZodiac: rawData.chineseZodiac || '未设置',
      maritalStatus: rawData.maritalStatus || '未设置',
      education: rawData.education || '未设置',
      occupation: rawData.occupation || '未设置',
      isPartyMember: rawData.isPartyMember || false,
      hometown: rawData.hometown || '未设置',
      currentResidence: rawData.currentResidence || '未设置',
      assets: rawData.assets || {
        annualIncome: 0,
        car: '未设置',
        house: '未设置'
      },
      familyMembers: rawData.familyMembers || {
        familyType: '未设置',
        fatherDetail: { age: 0, desc: '未设置' },
        motherDetail: { age: 0, desc: '未设置' },
        otherDetail: []
      },
      avatarConfig: avatarConfig,
      isOnline: Math.random() > 0.5 // 模拟在线状态
    }
  },

  /**
   * 根据生日计算年龄
   */
  calculateAgeFromBirthDate(birthDate) {
    if (!birthDate) return 0
    const today = new Date()
    const birth = new Date(birthDate)
    let age = today.getFullYear() - birth.getFullYear()
    const monthDiff = today.getMonth() - birth.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--
    }
    return age
  },

  /**
   * 生成默认头像配置
   */
  generateDefaultAvatar(gender) {
    if (gender === '男') {
      return {
        type: 'male',
        faceShape: 'square',
        skinTone: 'light',
        hairStyle: 'short_neat',
        eyeStyle: 'confident',
        accessory: 'none',
        clothing: 'formal_shirt',
        expression: 'smile'
      }
    } else {
      return {
        type: 'female', 
        faceShape: 'oval',
        skinTone: 'light',
        hairStyle: 'long_wavy',
        eyeStyle: 'gentle',
        accessory: 'earrings',
        clothing: 'elegant_dress',
        expression: 'sweet_smile'
      }
    }
  },

  /**
   * 显示空状态
   */
  showEmptyState() {
    this.setData({
      userProfile: {
        ...this.data.userProfile,
        name: '用户不存在',
        gender: '未知',
        age: 0,
        height: 0,
        weight: 0
      }
    })
  },

  /**
   * 编辑资料
   */
  editProfile() {
    this.setData({ isEditMode: true })
    this.initEditMode()
  },

  /**
   * 查看详细信息
   */
  showDetailInfo() {
    wx.showModal({
      title: '详细信息',
      content: `用户编号：${this.data.userProfile.userNum}\n创建时间：${this.data.userProfile.createTime || '未知'}\n修改时间：${this.data.userProfile.modifyTime || '未知'}`,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 初始化城市数据
   */
  initCities() {
    const { cities, formData } = this.data
    const filteredCities = cities.map(city => ({
      name: city,
      cityClass: city === formData.currentCity ? 'selected' : ''
    }))

    this.setData({
      filteredCities: filteredCities
    })
  },

  /**
   * 编辑头像
   */
  editAvatar() {
    wx.navigateTo({
      url: '/pages/avatar/avatar?edit=true'
    })
  },

  /**
   * 保存资料
   */
  saveProfile() {
    if (!this.validateForm()) return

    this.setData({ showSaveDialog: true })
  },

  /**
   * 更新计算属性
   */
  updateComputedProperties() {
    const { formData, activeCategory } = this.data

    this.setData({
      genderText: formData.gender === 'male' ? '男' : '女',
      birthdayText: formData.birthday || '请选择生日',
      cityText: formData.currentCity || '请选择城市',
      educationText: formData.education || '请选择学历',
      statementLength: formData.personalStatement ? formData.personalStatement.length : 0,
      selectedCity: formData.currentCity,

      // 更新分类激活状态
      sportsActive: activeCategory === 'sports' ? 'active' : '',
      musicActive: activeCategory === 'music' ? 'active' : '',
      travelActive: activeCategory === 'travel' ? 'active' : '',
      foodActive: activeCategory === 'food' ? 'active' : '',
      readingActive: activeCategory === 'reading' ? 'active' : '',
      movieActive: activeCategory === 'movie' ? 'active' : ''
    })
  },

  /**
   * 加载用户资料显示
   */
  loadUserProfile() {
    this.setData({ loading: true })

    // 模拟加载数据，实际应该从 API 获取
    setTimeout(() => {
      const app = getApp()
      const globalUserInfo = app.globalData.userInfo || {}

      // 计算年龄
      let age = 26
      if (globalUserInfo.birthday) {
        age = calculateAge(globalUserInfo.birthday)
      }

      this.setData({
        userProfile: {
          nickname: globalUserInfo.nickname || '林小雨',
          gender: globalUserInfo.gender || 'female',
          age: age,
          height: globalUserInfo.height || 165,
          currentCity: globalUserInfo.currentCity || '上海',
          education: globalUserInfo.education || '硕士',
          occupation: globalUserInfo.occupation || '医生',
          personalStatement: globalUserInfo.personalStatement || '热爱生活，喜欢旅行和摄影。希望找到一个有趣的灵魂一起探索世界。',
          avatarUrl: globalUserInfo.avatarUrl || '',
          isOnline: true
        },
        loading: false
      })
    }, 500)
  },

  /**
   * 初始化编辑模式（保留原有编辑功能）
   */
  initEditMode() {
    // 这里可以保留原有的编辑功能逻辑
    this.loadProfile()
  },

  /**
   * 编辑资料
   */
  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/profile?edit=true'
    })
  },

  /**
   * 查看详细信息
   */
  showDetailInfo() {
    console.log('查看详细信息')
  },

  /**
   * 导航到设置页面
   */
  navigateToSettings(e) {
    const type = e.currentTarget.dataset.type

    switch (type) {
      case 'account':
        wx.navigateTo({
          url: '/pages/user-center/user-center'
        })
        break
      case 'privacy':
        wx.navigateTo({
          url: '/pages/privacy-settings/privacy-settings'
        })
        break
      case 'preferences':
        wx.navigateTo({
          url: '/pages/match-preferences/match-preferences'
        })
        break
      default:
        showError('功能暂未开放')
    }
  },

  // 编辑模式的加载方法（保留原有功能）
  loadProfile() {
    if (!this.data.isEditMode) return;

    this.setData({ loading: true });

    get('/api/user/profile')
      .then(data => {
        this.setData({
          formData: { ...this.data.formData, ...data },
          loading: false
        });

        if (data.interests && Array.isArray(data.interests)) {
          this.loadUserInterests(data.interests);
        }

        this.calculateCompletion();
      })
      .catch((error) => {
        console.error('加载资料失败:', error);
        this.setData({ loading: false });
      });
  },

  loadUserInterests(userInterests) {
    // 设置已选兴趣
    this.setData({
      selectedInterests: userInterests
    });

    // 更新当前分类的兴趣显示状态
    this.updateCurrentInterestsDisplay();
  },

  updateCurrentInterestsDisplay() {
    const { currentInterests, selectedInterests } = this.data;

    const updatedCurrentInterests = currentInterests.map(interest => ({
      ...interest,
      selected: selectedInterests.some(selected => selected.id === interest.id),
      selectedClass: selectedInterests.some(selected => selected.id === interest.id) ? 'selected' : ''
    }));

    this.setData({
      currentInterests: updatedCurrentInterests
    });
  },

  initInterests() {
    // 初始化完整的兴趣数据
    const allInterests = {
      sports: [
        { id: 'running', name: '跑步' },
        { id: 'swimming', name: '游泳' },
        { id: 'fitness', name: '健身' },
        { id: 'basketball', name: '篮球' },
        { id: 'football', name: '足球' },
        { id: 'tennis', name: '网球' },
        { id: 'badminton', name: '羽毛球' },
        { id: 'volleyball', name: '排球' },
        { id: 'cycling', name: '骑行' },
        { id: 'hiking', name: '循山' }
      ],
      music: [
        { id: 'pop', name: '流行音乐' },
        { id: 'classical', name: '古典音乐' },
        { id: 'rock', name: '摇滚音乐' },
        { id: 'jazz', name: '爵士音乐' },
        { id: 'guitar', name: '吉他' },
        { id: 'piano', name: '钢琴' },
        { id: 'singing', name: '唱歌' },
        { id: 'karaoke', name: 'KTV' }
      ],
      travel: [
        { id: 'domestic', name: '国内旅行' },
        { id: 'international', name: '出国旅行' },
        { id: 'backpacking', name: '背包旅行' },
        { id: 'photography', name: '旅行摄影' },
        { id: 'camping', name: '露营' },
        { id: 'road_trip', name: '自驾游' },
        { id: 'cultural', name: '文化旅行' }
      ],
      food: [
        { id: 'cooking', name: '烹饪' },
        { id: 'baking', name: '烘焙' },
        { id: 'fine_dining', name: '美食品鉴' },
        { id: 'street_food', name: '街头美食' },
        { id: 'dessert', name: '甜品' },
        { id: 'coffee', name: '咖啡' },
        { id: 'tea', name: '茶道' },
        { id: 'wine', name: '红酒' }
      ],
      reading: [
        { id: 'fiction', name: '小说' },
        { id: 'non_fiction', name: '非虚构' },
        { id: 'biography', name: '传记' },
        { id: 'history', name: '历史' },
        { id: 'science', name: '科学' },
        { id: 'philosophy', name: '哲学' },
        { id: 'poetry', name: '诗歌' },
        { id: 'magazine', name: '杂志' }
      ],
      movie: [
        { id: 'action', name: '动作片' },
        { id: 'comedy', name: '喜剧片' },
        { id: 'romance', name: '爱情片' },
        { id: 'thriller', name: '悬疑片' },
        { id: 'documentary', name: '纪录片' },
        { id: 'animation', name: '动画片' },
        { id: 'foreign', name: '外语片' },
        { id: 'classic', name: '经典电影' }
      ],
      art: [
        { id: 'painting', name: '绘画' },
        { id: 'calligraphy', name: '书法' },
        { id: 'sculpture', name: '雕塑' },
        { id: 'photography', name: '摄影' },
        { id: 'design', name: '设计' },
        { id: 'craft', name: '手工艺' }
      ],
      technology: [
        { id: 'programming', name: '编程' },
        { id: 'ai', name: '人工智能' },
        { id: 'blockchain', name: '区块链' },
        { id: 'gaming', name: '游戏' },
        { id: 'gadgets', name: '数码产品' }
      ]
    };

    this.setData({
      allInterests,
      currentInterests: allInterests[this.data.activeCategory] || allInterests.sports
    });
  },

  onFieldChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value,
      hasChanges: true
    })
    this.updateComputedProperties()
    this.calculateCompletion()
  },

  onTextareaInput(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value,
      hasChanges: true
    })
    this.updateComputedProperties()
  },

  calculateCompletion() {
    const { formData, selectedInterests } = this.data;

    // 必填字段（50%权重）
    const requiredFields = ['nickname', 'gender', 'birthday', 'height', 'currentCity', 'education', 'occupation'];
    const completedRequired = requiredFields.filter(field => formData[field] && formData[field].trim());
    const requiredScore = (completedRequired.length / requiredFields.length) * 50;

    // 可选字段（30%权重）
    const optionalFields = ['company', 'monthlyIncome', 'housing', 'relationshipView', 'personalStatement'];
    const completedOptional = optionalFields.filter(field => formData[field] && formData[field].trim());
    const optionalScore = (completedOptional.length / optionalFields.length) * 30;

    // 兴趣爱好（20%权重）
    const interestScore = Math.min(selectedInterests.length / 5, 1) * 20; // 至少 5 个兴趣才算满分

    const totalScore = Math.round(requiredScore + optionalScore + interestScore);

    this.setData({
      completionRate: totalScore,
      completionDetails: {
        required: {
          score: Math.round(requiredScore),
          completed: completedRequired.length,
          total: requiredFields.length
        },
        optional: {
          score: Math.round(optionalScore),
          completed: completedOptional.length,
          total: optionalFields.length
        },
        interests: {
          score: Math.round(interestScore),
          completed: selectedInterests.length,
          recommended: 5
        }
      }
    });
  },

  // 选择器方法
  showGenderPicker() {
    this.setData({ showGenderPopup: true })
  },

  hideGenderPicker() {
    this.setData({ showGenderPopup: false })
  },

  onGenderConfirm(e) {
    const value = e.detail.value
    this.setData({
      'formData.gender': value,
      showGenderPopup: false,
      hasChanges: true
    })
    this.updateComputedProperties()
    this.calculateCompletion()
  },

  showDatePicker() {
    const birthday = this.data.formData.birthday
    if (birthday) {
      this.setData({ selectedDate: new Date(birthday).getTime() })
    }
    this.setData({ showDatePopup: true })
  },

  hideDatePicker() {
    this.setData({ showDatePopup: false })
  },

  onDateConfirm(e) {
    const date = new Date(e.detail.value)
    const birthday = date.toISOString().split('T')[0]
    this.setData({
      'formData.birthday': birthday,
      showDatePopup: false,
      hasChanges: true
    })
    this.updateComputedProperties()
    this.calculateCompletion()
  },

  showCityPicker() {
    this.setData({ showCityPopup: true })
  },

  hideCityPicker() {
    this.setData({ showCityPopup: false })
  },

  onCitySearch(e) {
    const keyword = e.detail.value.toLowerCase()
    const { cities, formData } = this.data
    const filtered = cities.filter(city =>
      city.toLowerCase().includes(keyword)
    ).map(city => ({
      name: city,
      cityClass: city === formData.currentCity ? 'selected' : ''
    }))

    this.setData({
      citySearchKeyword: keyword,
      filteredCities: filtered
    })
  },

  selectCity(e) {
    const city = e.currentTarget.dataset.city
    this.setData({
      'formData.currentCity': city,
      hasChanges: true
    })
    this.updateComputedProperties()
    this.initCities() // 重新初始化城市列表以更新选中状态
    this.calculateCompletion()
  },

  confirmCity() {
    this.setData({ showCityPopup: false })
  },

  // 其他选择器方法
  showEducationPicker() {
    this.setData({ showEducationPopup: true });
  },

  hideEducationPicker() {
    this.setData({ showEducationPopup: false });
  },

  onEducationConfirm(e) {
    const value = e.detail.value;
    const educationMap = {
      'highschool': '高中及以下',
      'college': '大专',
      'bachelor': '本科',
      'master': '硕士',
      'doctor': '博士'
    };
    this.setData({
      'formData.education': educationMap[value] || value,
      showEducationPopup: false,
      hasChanges: true
    });
    this.updateComputedProperties();
    this.calculateCompletion();
  },

  showIncomePicker() {
    this.setData({ showIncomePopup: true });
  },

  hideIncomePicker() {
    this.setData({ showIncomePopup: false });
  },

  onIncomeConfirm(e) {
    const value = e.detail.value;
    const incomeMap = {
      '<3k': '3K以下',
      '3k-5k': '3K-5K',
      '5k-10k': '5K-10K',
      '10k-20k': '10K-20K',
      '>20k': '20K以上'
    };
    this.setData({
      'formData.monthlyIncome': incomeMap[value] || value,
      showIncomePopup: false,
      hasChanges: true
    });
  },

  showHousingPicker() {
    this.setData({ showHousingPopup: true });
  },

  hideHousingPicker() {
    this.setData({ showHousingPopup: false });
  },

  onHousingConfirm(e) {
    const value = e.detail.value;
    const housingMap = {
      'rent': '租房',
      'owned': '已购房',
      'family': '家庭住房'
    };
    this.setData({
      'formData.housing': housingMap[value] || value,
      showHousingPopup: false,
      hasChanges: true
    });
  },

  showRelationshipPicker() {
    this.setData({ showRelationshipPopup: true });
  },

  hideRelationshipPicker() {
    this.setData({ showRelationshipPopup: false });
  },

  onRelationshipConfirm(e) {
    const value = e.detail.value;
    const relationshipMap = {
      'serious': '认真交往',
      'casual': '随缘发展',
      'friends_first': '先做朋友'
    };
    this.setData({
      'formData.relationshipView': relationshipMap[value] || value,
      showRelationshipPopup: false,
      hasChanges: true
    });
  },

  // 兴趣管理方法
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    const interests = this.data.allInterests[category] || [];

    this.setData({
      activeCategory: category,
      currentInterests: interests
    });

    // 更新显示状态
    this.updateCurrentInterestsDisplay();
    this.updateComputedProperties();
  },

  toggleInterest(e) {
    const interestId = e.currentTarget.dataset.interestId;
    const { currentInterests, selectedInterests } = this.data;

    // 找到点击的兴趣
    const interest = currentInterests.find(item => item.id === interestId);
    if (!interest) return;

    const isSelected = selectedInterests.some(item => item.id === interestId);

    if (isSelected) {
      // 取消选中
      this.removeInterest(e);
    } else {
      // 添加选中
      if (selectedInterests.length >= 10) {
        showError('最多只能选择 10 个兴趣');
        return;
      }

      const newSelectedInterests = [...selectedInterests, {
        id: interest.id,
        name: interest.name,
        category: this.data.activeCategory
      }];

      // 更新当前兴趣显示状态
      const updatedCurrentInterests = currentInterests.map(item => ({
        ...item,
        selected: item.id === interestId ? true : item.selected
      }));

      this.setData({
        selectedInterests: newSelectedInterests,
        currentInterests: updatedCurrentInterests,
        hasChanges: true
      });
    }
  },

  removeInterest(e) {
    const interestId = e.currentTarget.dataset.interestId;
    const { selectedInterests, currentInterests } = this.data;

    // 从已选列表中移除
    const newSelectedInterests = selectedInterests.filter(item => item.id !== interestId);

    // 更新当前兴趣显示状态
    const updatedCurrentInterests = currentInterests.map(item => ({
      ...item,
      selected: item.id === interestId ? false : item.selected
    }));

    this.setData({
      selectedInterests: newSelectedInterests,
      currentInterests: updatedCurrentInterests,
      hasChanges: true
    });
  },

  // 增强的表单验证
  validateForm() {
    const { formData } = this.data;
    const required = ['nickname', 'gender', 'birthday', 'height', 'currentCity', 'education', 'occupation'];

    // 基本必填字段验证
    for (let field of required) {
      if (!formData[field]) {
        showError(`请填写${this.getFieldName(field)}`);
        return false;
      }
    }

    // 昵称验证
    if (formData.nickname.trim().length < 2) {
      showError('昵称至少需要 2 个字符');
      return false;
    }

    if (formData.nickname.trim().length > 20) {
      showError('昵称不能超过 20 个字符');
      return false;
    }

    // 身高验证
    const height = parseInt(formData.height);
    if (isNaN(height) || height < 100 || height > 250) {
      showError('身高请填写 100-250cm 之间的数字');
      return false;
    }

    // 生日验证
    const birthday = new Date(formData.birthday);
    const now = new Date();
    const age = now.getFullYear() - birthday.getFullYear();

    if (age < 18) {
      showError('年龄不能小于 18 岁');
      return false;
    }

    if (age > 100) {
      showError('请输入正确的出生日期');
      return false;
    }

    // 职业验证
    if (formData.occupation.trim().length < 2) {
      showError('请输入正确的职业信息');
      return false;
    }

    // 个人简介验证（如果填写）
    if (formData.personalStatement && formData.personalStatement.trim().length > 500) {
      showError('个人简介不能超过 500 个字符');
      return false;
    }

    return true;
  },

  // 显示身高提示
  showHeightTip() {
    wx.showModal({
      title: '身高填写说明',
      content: '请输入您的真实身高（单位：cm），范围为 100-250cm。\n\n真实的身高信息有助于更好的匹配。',
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  saveProfile() {
    if (!this.validateForm()) return

    this.setData({ showSaveDialog: true })
  },

  validateForm() {
    const { formData } = this.data
    const required = ['nickname', 'gender', 'birthday', 'height', 'currentCity', 'education', 'occupation']

    for (let field of required) {
      if (!formData[field]) {
        showError(`请填写${this.getFieldName(field)}`)
        return false
      }
    }

    if (formData.height && (formData.height < 100 || formData.height > 250)) {
      showError('身高请填写100-250cm之间')
      return false
    }

    return true
  },

  getFieldName(field) {
    const names = {
      nickname: '昵称',
      gender: '性别',
      birthday: '生日',
      height: '身高',
      currentCity: '城市',
      education: '学历',
      occupation: '职业'
    }
    return names[field] || field
  },

  confirmSave() {
    this.setData({ loading: true, showSaveDialog: false });

    // 准备同步数据，转换为API要求的格式
    const syncData = this.transformFormDataToSyncFormat();

    console.log('🚀 准备同步用户资料:', JSON.stringify(syncData, null, 2));

    syncUserProfile(syncData, {
      showLoading: true,
      loadingTitle: '保存资料中...'
    })
      .then((response) => {
        console.log('✅ 用户资料同步成功:', response);
        showSuccess('资料保存成功');
        this.setData({ hasChanges: false, loading: false });

        // 更新全局用户信息
        const app = getApp();
        if (app.updateUserProfile) {
          app.updateUserProfile(this.data.formData);
        }

        // 显示完成度提示
        if (this.data.completionRate === 100) {
          setTimeout(() => {
            wx.showModal({
              title: '恭喜！',
              content: '您的资料已完全填写，现在可以开始您的所恋之旅了！',
              showCancel: false,
              confirmText: '开始交友',
              success: (res) => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/discovery/discovery'
                  });
                }
              }
            });
          }, 1000);
        } else {
          // 返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(error => {
        console.error('❌ 用户资料同步失败:', error);
        showError('保存失败，请重试');
        this.setData({ loading: false });
      });
  },

  /**
   * 将表单数据转换为同步API要求的格式
   */
  transformFormDataToSyncFormat() {
    const { formData } = this.data;
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};

    // 教育背景映射
    const educationMap = {
      '高中及以下': '高中',
      '大专': '专科',
      '本科': '本科',
      '硕士': '硕士',
      '博士': '博士'
    };

    // 性别映射
    const genderMap = {
      'male': '男',
      'female': '女'
    };

    // 婚姻状态映射（默认未婚）
    const maritalStatus = '未婚';

    // 收入转换为数值（万元）
    const annualIncome = this.convertIncomeToNumber(formData.monthlyIncome);

    // 房产状况转换
    const houseStatus = this.convertHousingToStatus(formData.housing);

    return {
      userNum: userInfo.userNum || 0,
      name: formData.nickname || '',
      gender: genderMap[formData.gender] || formData.gender || '',
      height: parseInt(formData.height) || 0,
      weight: 0, // 暂时默认值，后续可以添加体重字段
      birthDate: formData.birthday || '',
      maritalStatus: maritalStatus,
      assets: {
        annualIncome: annualIncome,
        car: '', // 暂时默认值，后续可以添加车辆字段
        house: houseStatus
      },
      education: educationMap[formData.education] || formData.education || '',
      occupation: formData.occupation || '',
      isPartyMember: false, // 暂时默认值，后续可以添加党员字段
      hometown: '', // 暂时默认值，后续可以添加籍贯字段
      currentResidence: formData.currentCity || '',
      familyMembers: {
        familyType: '',
        fatherDetail: { age: 0, desc: '' },
        motherDetail: { age: 0, desc: '' },
        otherDetail: []
      },
      createUser: 'miniprogram',
      modifyUser: 'miniprogram'
    };
  },

  /**
   * 将月收入转换为年收入（万元）
   */
  convertIncomeToNumber(monthlyIncome) {
    if (!monthlyIncome) return 0;

    const incomeMap = {
      '<3k': 3,
      '3k-5k': 5,
      '5k-10k': 10,
      '10k-20k': 20,
      '>20k': 25
    };

    return incomeMap[monthlyIncome] || 0;
  },

  /**
   * 将住房状况转换为API格式
   */
  convertHousingToStatus(housing) {
    if (!housing) return '';

    const housingMap = {
      'rent': '无',
      'owned': '城区全款房',
      'family': '乡镇房'
    };

    return housingMap[housing] || '';
  },

  cancelSave() {
    this.setData({ showSaveDialog: false })
  },

  goBack() {
    if (this.data.hasChanges) {
      wx.showModal({
        title: '确认离开',
        content: '你有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    } else {
      wx.navigateBack()
    }
  }
})